package com.nic.view.widget;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * Created by Administrator on 2018/11/7.
 */

public class AQPopupWindow extends PopupWindow {
    private Context cxt;

    public AQPopupWindow(View contentView, int width, int height, boolean focusable) {
        super(contentView, width, height, focusable);
        this.cxt = contentView.getContext();
    }


    public AQPopupWindow(Context context) {
        super(context);
    }


    public void show(View parent) {
        if (Build.VERSION.SDK_INT < 24) {
            showAsDropDown(parent, 0, 0);
        } else {
            int[] a = new int[2];
            parent.getLocationInWindow(a);
            //a[0] - parent.getWidth(), parent.getHeight() + a[1]

            showAtLocation(parent, Gravity.NO_GRAVITY, a[0], a[1]);
            update();
        }

    }

    @Override
    public void dismiss() {
        super.dismiss();
        setBackground((Activity) cxt, 1.0f);
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        setBackground((Activity) cxt, 0.8f);
    }

    @Override
    public void showAsDropDown(View anchor) {
//        if (Build.VERSION.SDK_INT >= 24) {
//            Rect rect = new Rect();
//            anchor.getGlobalVisibleRect(rect);
//            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
//            setHeight(h);
//        }
        super.showAsDropDown(anchor);
        setBackground((Activity) cxt, 0.8f);
    }

    public void showAsDropDown(View anchor, boolean shadow) {
//        if (Build.VERSION.SDK_INT >= 24) {
//            Rect rect = new Rect();
//            anchor.getGlobalVisibleRect(rect);
//            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
//            setHeight(h);
//        }
        super.showAsDropDown(anchor);
        if (shadow) {
            setBackground((Activity) cxt, 0.8f);
        }

    }

    public void setBackground(Activity context, float alpha) {
        if (context == null || context.isFinishing()) {
            return;
        }
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = alpha;
        context.getWindow().setAttributes(lp);
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
}
